package com.sion.servicekeep;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class AutoStartReceiver extends BroadcastReceiver {
    private static final String TAG = "AutoStartReceiver";
    private static final String PREF_NAME = "AppSettings";
    private static final String KEY_AUTO_START = "auto_start_enabled";
    private static final String KEY_STARTUP_DELAY = "startup_delay"; // 新增键名

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "=== AutoStartReceiver triggered ===");
        Log.d(TAG, "Received broadcast: " + action);
        Log.d(TAG, "Package: " + context.getPackageName());
        Log.d(TAG, "Intent extras: " + intent.getExtras());

        if (action == null) {
            Log.w(TAG, "Received null action, ignoring");
            return;
        }

        if (Intent.ACTION_BOOT_COMPLETED.equals(action) ||
                Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action) ||
                "android.intent.action.QUICKBOOT_POWERON".equals(action)) {

            Log.d(TAG, "Boot completed event received");
            handleBootCompleted(context);

        } else if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(action) ||
                Intent.ACTION_PACKAGE_REPLACED.equals(action)) {

            Log.d(TAG, "Package replaced event received");
            handlePackageReplaced(context, intent);

        } else {
            Log.d(TAG, "Unhandled action: " + action);
        }
    }

    private void handleBootCompleted(Context context) {
        Log.d(TAG, "Processing boot completed event");

        try {
            // 检查用户是否启用了开机自启动
            SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            boolean isAutoStartEnabled = sharedPreferences.getBoolean(KEY_AUTO_START, false);

            Log.d(TAG, "Auto start enabled from preferences: " + isAutoStartEnabled);

            if (isAutoStartEnabled) {
                Log.d(TAG, "Auto start is enabled, preparing to start services");

                // 获取开机延迟启动时间
                int startupDelay = sharedPreferences.getInt(KEY_STARTUP_DELAY, 3); // 默认值为3秒
                long delayMillis = startupDelay * 1000;

                // 延迟启动，给系统一些时间完成启动
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    Log.d(TAG, "Delayed start triggered after " + startupDelay + " seconds");
                    startAppServices(context);
                }, delayMillis);

            } else {
                Log.d(TAG, "Auto start is disabled, ignoring boot event");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in handleBootCompleted: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void handlePackageReplaced(Context context, Intent intent) {
        try {
            // 检查是否是自己的包被替换
            String packageName = intent.getDataString();
            Log.d(TAG, "Package replaced: " + packageName);

            if (packageName != null && packageName.contains(context.getPackageName())) {
                Log.d(TAG, "Our package was replaced, checking auto start");
                handleBootCompleted(context); // 复用相同的逻辑
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in handlePackageReplaced: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void startAppServices(Context context) {
        Log.d(TAG, "Starting app services...");

        // 1. 首先启动前台服务
        try {
            Intent serviceIntent = new Intent(context, ForegroundService.class);
            serviceIntent.putExtra("startedBy", "AutoStartReceiver");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
                Log.d(TAG, "Started foreground service via startForegroundService");
            } else {
                context.startService(serviceIntent);
                Log.d(TAG, "Started service via startService");
            }

        } catch (Exception e) {
            Log.e(TAG, "Failed to start ForegroundService: " + e.getMessage());
            e.printStackTrace();
        }

        // 2. 启动主活动进行测试
        try {
            Intent activityIntent = new Intent(context, MainActivity.class);
            activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            activityIntent.putExtra("startedBy", "AutoStartReceiver");

            context.startActivity(activityIntent);
            Log.d(TAG, "MainActivity started successfully");

        } catch (Exception e) {
            Log.e(TAG, "Failed to start MainActivity: " + e.getMessage());
            e.printStackTrace();
        }

        Log.d(TAG, "App services startup process completed");
    }
}